package com.datastructure.test.minofsumofpath;

public class Solution {

    public static void main(String[] args) {
        int[][] arr = new int[4][4];
        arr[0]=new int[]{1,3,5,9};
        arr[1]=new int[]{8,1,3,4};
        arr[2]=new int[]{5,0,6,1};
        arr[3]=new int[]{8,8,4,0};
        Solution solution = new Solution();
        int i = solution.minPathSum(arr);
        System.out.println(i);
    }

    public int minPathSum (int[][] matrix) {
        // write code here
        int[][] temp = new int[matrix.length][matrix[0].length];
        temp[0][0]=matrix[0][0];
        int left = 0;
        int top = 0;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if((i==0)&&(j-1>=0)){
                    temp[i][j]=matrix[i][j]+temp[i][j-1];
                } else
                if((j==0)&&(i-1>=0)){
                    temp[i][j]=matrix[i][j]+temp[i-1][j];
                }
                else if(i>0) {
                    top = temp[i - 1][j] ;
                    left = temp[i][j - 1] ;
                    temp[i][j] = Math.min(matrix[i][j] + top, matrix[i][j] + left);
                }
            }
        }
        return temp[matrix.length-1][matrix[0].length-1];
    }
}
